from turbogears import validators
import sqlobject
import model

class GeoLocation(validators.NotEmpty):

    messages = {
        'invalid': 'Invalid Geolocation'
    }

    def _to_python(self, value, state):
        if isinstance(value, dict):
            return value
        def parse_point(value):
            return map(float, value.replace('(','').replace(')','').split(','))
        try:
            coords = unicode(value).strip().split(':')
            point = parse_point(coords[0])
            center = parse_point(coords[1])
            zoom = float(coords[2])
            return dict(lat=point[0],
                              lng=point[1],
                              center_lat=center[0],
                              center_lng=center[1],
                              zoom=zoom
                              )
        except (KeyError, AttributeError, TypeError, IndexError, ValueError), e:
            raise validators.Invalid, \
                    (self.message('invalid', state), value, state)

    def _from_python(self, value, state):
        if isinstance(value, dict):
            return "(%s, %s):(%s, %s):%s" % (value['lat'], value['lng'],
                                             value['center_lat'], value['center_lng'],
                                             value['zoom'])
        return str(value)
